package models

import (
	"3rd/errors"
	"3rd/mongo"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	goerrors "github.com/go-errors/errors"
	"time"
)

type Device struct {
	Sn      string `bson:"_id" json:"sn"`
	Created int64  `bson:"created,omitempty" json:"created"`
}

func Import(sns []string) error {
	t := time.Now().Unix()

	return mongo.DO(db_device, col_device, func(c *mgo.Collection) error {
		bulk := c.Bulk()
		for _, val := range sns {
			bulk.Insert(Device{Sn: val, Created: t})
		}
		if _, err := bulk.Run(); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func Export(sns *[]string) error {
	return nil
}

func ValidateSn(sn string) error {
	return mongo.DO(db_device, col_device, func(c *mgo.Collection) error {
		var dev Device
		if err := c.FindId(sn).Select(bson.M{"_id": 1}).One(&dev); err != nil || dev.Sn == "" {
			// TODO:
			return errors.New(Dev_InvalidDev, err)
		}
		return nil
	})
}

func HeartBeat(sn string) error {
	expire := 2 * time.Duration(HbInterval) * time.Second
	if v, ok := timers[sn]; ok {
		v.Reset(expire)
	} else {
		if err := SetStatus(sn, 1); err != nil {
			return goerrors.New(err)
		}
		timers[sn] = time.AfterFunc(expire, func() {
			delete(timers, sn)
			SetStatus(sn, 0)
		})
	}
	return nil
}
